import {Button, Card, Form, Space} from 'antd';
import React, {useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import "./index.css";
import {formSetFieldsValue, jumpPage} from "@/assets/utils/utils";
import {FormLayoutProps} from "@/assets/components/formLayoutProps";
import {handleSave} from "@/assets/components/tableList";
import {useRequest} from "@@/plugin-request/request";
import {get} from "@/assets/service/baseService";
import {DataEntity} from "@/assets/entity/base";

/**
 * form单页面页面组件
 * @param props
 * @constructor
 */
const FormLayout = (props:FormLayoutProps) => {

  const form = props.form || Form.useForm()[0];
  // 标题前缀
  let titlePrefix;
  if(props.id !== "0"){
    titlePrefix = props.editTitlePrefix ? props.editTitlePrefix : "编辑";
  }else {
    titlePrefix = props.addTitlePrefix ? props.addTitlePrefix : "新建";
  }

  const getRun = useRequest((id:string) => get(props.moduleUrl, id), {
    manual: true,
    onSuccess: (result:DataEntity) => {
      formSetFieldsValue(form, result)
      props.initCallback && props.initCallback(result);
      props.getData && props.getData(result)
    }
  }).run

  /**
   * 启动加载
   */
  useEffect(() => {
    if(props.id !== "0"){
      getRun(props.id)
    }
  }, []);

  return (
    <PageContainer title={titlePrefix + props.title}>
      <Card bordered={false} title={props.title + "信息"}>
        <Form
          layout={"vertical"}
          form={form}
          preserve={false}
        >
          {props.children}
          <Form.Item style={{textAlign: "right"}}>
            <Space>
              <Button onClick={() => jumpPage(props.jumpPage || props.moduleUrl)}>取消</Button>
              <Button type="primary" onClick={()=>{
                props.saveFunction ? props.saveFunction() : handleSave(form, props.moduleUrl, undefined, undefined, ()=>{
                  jumpPage(props.jumpPage || props.moduleUrl)
                })
              }}>确定</Button>
            </Space>
          </Form.Item>
          <Form.Item
            initialValue={props.id !== "0" ? props.id : undefined}
            key="id"
            name="id"
            className={"formItemHidden"}>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  )
};

export default FormLayout;
